package com.spatio.serving.basic.service.template.server.Interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.spatio.serving.basic.service.template.common.domain.UserLoginDo;
import com.spatio.serving.basic.service.template.common.util.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Base64;
import java.util.HashMap;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<UserLoginDo> userLoginDoThreadLocal = new ThreadLocal<>();


    //解析token
    private UserLoginDo parseAuthHeader(String authHeader) throws JsonProcessingException {
        // 示例解析，具体实现根据 auth 字段的格式来决定
        // 假设 authHeader 是 JSON 格式的字符串
        // 例如: {"userId": "12345", "username": "JohnDoe"}
        String payload = JwtUtils.decode(authHeader).getPayload();
        byte[] decodedBytes = Base64.getDecoder().decode(payload);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(new String(decodedBytes));
        UserLoginDo user=new UserLoginDo();
        user.setUser_id(new BigInteger(jsonNode.get("user_id").asText()));
        return user;
    }

    public static UserLoginDo getUserInfo() {
        return userLoginDoThreadLocal.get();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        System.out.println(token);
        HashMap<String, Object> map = new HashMap<>();
        try {
            JwtUtils.decode(token);
            //从token中解析出payload的内容
//            String payload = JwtUtils.decode(token).getPayload();
//            byte[] decodedBytes = Base64.getDecoder().decode(payload);
//            System.out.println("_______________");
//            System.out.println(new String(decodedBytes));
            UserLoginDo userLogin = parseAuthHeader(token);
            userLoginDoThreadLocal.set(userLogin);
            return true;    // 验证成功，则返回true，表示放行
        } catch (TokenExpiredException e) {

            map.put("code", 401);
            map.put("message", "Token已经过期！");
            map.put("data", null);
        }catch (SignatureVerificationException e) {
            map.put("code", 401);
            map.put("message", "签名错误！");
            map.put("data", null);
        }catch (AlgorithmMismatchException e) {
            map.put("code", 401);
            map.put("message", "加密算法不匹配！");
            map.put("data", null);
        }catch (Exception e) {
            map.put("code", 401);
            map.put("message", "无效token");
            map.put("data", null);
        }

        // jackson 将 map 转成 json字符串
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);

        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        userLoginDoThreadLocal.remove();
    }



}

